package com.example.blog.auth;

import cn.hutool.core.util.ArrayUtil;

import com.example.blog.base.CurrentAccount;
import com.example.blog.exception.BusinessException;
import com.example.blog.exception.CommonErrorCode;
import com.example.blog.util.CurrentUserUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @ClassName HasPermissionHandel
 * @Description TODO
 * @Author Wang Li Hong
 * @date 2024/1/8 15:09
 * @Version 1.0
 */
@Aspect
@Component
public class HasPermissionHandel {
    @Before("@annotation(permission)")
    public void check(JoinPoint joinPoint, Permission permission) {
        String[] roles = permission.value();
        if (ArrayUtil.isEmpty(roles)) {
            throw new BusinessException(CommonErrorCode.LOGIN.getMessage(), CommonErrorCode.LOGIN.getCode());
        }
        CurrentAccount account = CurrentUserUtils.currentUser();
        if (account == null) {
            throw new BusinessException(CommonErrorCode.LOGIN.getMessage(), CommonErrorCode.LOGIN.getCode());
        }
        for (String role : roles) {
            if (Objects.equals(role, account.getRole())) {
                return;
            }
        }
        throw new BusinessException(CommonErrorCode.PERMISSIONS.getMessage(), CommonErrorCode.PERMISSIONS.getCode());
    }
}
